package com.example.presentshopping.ui.activity

import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.ImageView
import com.example.presentshopping.R
import com.example.presentshopping.config.base.BaseMvpActivity
import com.example.presentshopping.config.bean.AlipayBean
import com.example.presentshopping.jpay.JPay
import com.example.presentshopping.mvp.presenter.PublicPresenter
import com.example.presentshopping.net.http.HttpRequest
import com.example.presentshopping.net.http.HttpURL
import com.example.presentshopping.net.observer.TaskCallback
import com.example.presentshopping.ui.custom.PayPwdEditText
import com.example.presentshopping.utils.ToastUtil
import com.example.presentshopping.utils.tool.GsonUtils
import kotlinx.android.synthetic.main.activity_team.*
import kotlinx.android.synthetic.main.activity_team.click_alipay
import kotlinx.android.synthetic.main.activity_team.click_nowPay
import kotlinx.android.synthetic.main.activity_team.is_alipay
import kotlinx.android.synthetic.main.activity_team.is_nowPay
import kotlinx.android.synthetic.main.activity_team.title_main_tv

class TeamActivity : BaseMvpActivity() {
    private var walletDialog: Dialog? = null
    var order_id :String ?=null

    var pay = 1
    private var queryInfoPresenter: PublicPresenter? = null

    var aliPayBean : AlipayBean?=null

    override val layoutId: Int
        get() = R.layout.activity_team

    override fun initView(savedInstanceState: Bundle?) {

        queryInfoPresenter = PublicPresenter(this, true, "加载中...")
        queryInfoPresenter?.attachView(this)
        title_main_tv.leftBackImageTv.setOnClickListener { finish() }
        order_id =intent.getStringExtra("order_id")

        click_nowPay.setOnClickListener {
            is_nowPay.visibility = View.VISIBLE
            is_alipay.visibility = View.GONE
            pay = 1
        }
        click_alipay.setOnClickListener {
            is_nowPay.visibility = View.GONE
            is_alipay.visibility = View.VISIBLE
            pay = 2
        }
        dialog_spec_sel.setOnClickListener {
            when (pay) {
                1 -> {
                    showEditPayPwdDialog()
                }
                2 -> {
                    Orderalipay(order_id!!)
                }
            }
        }

    }


    override fun onDestroy() {
        queryInfoPresenter?.detachView()
        super.onDestroy()
    }

    override fun showToast(msg: String?) {
        ToastUtil.showMsg(msg)
    }

    override fun onSuccess(data: String?) {

    }

    override fun onFailure(e: Throwable?, code: Int, msg: String?, isNetWorkError: Boolean) {

    }

    //平台支付
    fun showEditPayPwdDialog() {
        val view: View = layoutInflater.inflate(R.layout.dialog_layout, null)
        walletDialog = Dialog(this, R.style.walletFrameWindowStyle)
        walletDialog!!.setContentView(
            view, ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT
            )
        )

        val window = walletDialog!!.window
        val wl = window!!.attributes

        //紧贴软键盘弹出
        wl.gravity = Gravity.BOTTOM
        // 以下这两句是为了保证按钮可以水平满屏
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT
        walletDialog!!.onWindowAttributesChanged(wl)
        walletDialog!!.setCanceledOnTouchOutside(false)
        walletDialog!!.show()


        //忘记密码 按钮
        view.findViewById<View>(R.id.tv_forgetPwd).setOnClickListener {
            startActivity(
                Intent(
                    this@TeamActivity,
                    SetupPayPwdCheckActivity::class.java
                )
            )
        }
        val ppet: PayPwdEditText = view.findViewById(R.id.dialog_ppet)
        val img_cancle = view.findViewById<ImageView>(R.id.img_cancle)
        //调用initStyle方法创建你需要设置的样式
        //调用initStyle方法创建你需要设置的样式
        ppet.initStyle(R.drawable.edit_num_bg, 6, 0.33f, R.color.gray, R.color.black, 30)
        img_cancle.setOnClickListener {
            walletDialog!!.dismiss()
            //手动收起软键盘
            val imm =
                getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(ppet.windowToken, 0)
            imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)

        }

        ppet.setOnTextFinishListener {
            //密码输入完后的回调
            walletDialog!!.dismiss()
            //手动收起软键盘
            val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(ppet.windowToken, 0)
            //可在此执行下一步操作
            val paypass = ppet.pwdText
            order_id?.let { it1 -> orderPlat(it1, paypass) }

        }
        //延迟弹起软键盘，使PayPwdEditText获取焦点
        Handler().postDelayed({ ppet.setFocus() }, 100)

    }

    //支付宝
    fun Orderalipay(orderid: String) {
        queryInfoPresenter?.netWorkRequestPost(
            HttpURL.Req_alipay,
            HttpRequest.orderalipay(orderid),
            object : TaskCallback {
                override fun onSuccess(data: String?) {
                    aliPayBean = GsonUtils.getGson().fromJson(data, AlipayBean().javaClass)
                    aliPay(aliPayBean?.data!!)
                }

                override fun onFailure(
                    e: Throwable?,
                    code: Int,
                    msg: String?,
                    isNetWorkError: Boolean
                ) {

                }

            })
    }

    //平台支付
    fun orderPlat(orderid: String, password: String) {
        queryInfoPresenter?.netWorkRequestPost(
            HttpURL.Req_orderPlatform, HttpRequest.orderPlatform(
            orderid,
            password
        ), object : TaskCallback {
            override fun onSuccess(data: String?) {
                showToast(" 成功加入拼团队列！")
                MainActivity.toStartActivity(this@TeamActivity)
                finish()
            }

            override fun onFailure(
                e: Throwable?,
                code: Int,
                msg: String?,
                isNetWorkError: Boolean
            ) {
                showToast(msg)
            }

        })
    }

    private fun aliPay(orderInfo: String) { // 支付宝支付
        JPay.getIntance(this).toPay(JPay.PayMode.ALIPAY, orderInfo, object : JPay.JPayListener {

            override fun onPaySuccess(resultStatus: String?) {
                MainActivity.toStartActivity(this@TeamActivity)
                finish()
            }

            override fun onPayError(error_code: Int, message: String) {
                showToast("支付失败")
                //  finish()
            }

            override fun onPayCancel() {
                showToast("取消了支付")
                //  finish()
            }
        })
    }


}